package me.android.library.ui.ext.views;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;

import androidx.annotation.NonNull;

import java.util.Objects;

import me.android.library.utils.android.HandlerUtil;

public class DelayEditText extends androidx.appcompat.widget.AppCompatEditText {

    public interface OnTextChangedCallback {
        void onTextChanged(String value);

        void onTextChangedWithoutDelay(String value);
    }


    static final int MSG_CODE = 98765;
    int msgCount = 0;
    long delayMillis = 1000 * 2;
    OnTextChangedCallback callabck;

    Handler handler;

    public DelayEditText(Context context) {
        super(context);
        init();
    }

    public DelayEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }


    public DelayEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    void init() {
        handler = HandlerUtil.createHandler(handleCallback);

        setSingleLine();
        setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        this.setOnEditorActionListener((v, actionId, event) ->
                actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
        );
    }


    public void setDelay(long delayMillis) {
        this.delayMillis = delayMillis;
    }

    public void setOnTextChangedCallback(OnTextChangedCallback callabck) {
        this.callabck = callabck;
    }

    @Override
    protected void onTextChanged(CharSequence text, int start,
                                 int lengthBefore, int lengthAfter) {
        if (!isInEditMode() && handler != null) {
            msgCount++;
            handler.sendEmptyMessageDelayed(MSG_CODE, delayMillis);
        }

        if (callabck != null) {
            callabck.onTextChangedWithoutDelay(text.toString());
        }
    }

    Handler.Callback handleCallback = new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == MSG_CODE) {
                if (msgCount == 1) {
                    msgCount = 0;
                    if (callabck != null) {
                        callabck.onTextChanged(Objects.requireNonNull(DelayEditText.this.getText()).toString());
                    }
                } else {
                    msgCount--;
                }
                return true;
            } else {
                return false;
            }
        }
    };

}
